package com.net

import com.netease.yunxin.kit.alog.ALog
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * Time:3/15/21 7:54 PM
 * Author:
 * Description:
 */
object RetrofitManager {
    var BASE_URL = "https://jiayin.greenamc.net/"
    private val okHttpClient by lazy {
        var trustAllCerts:Array<TrustManager> = arrayOf(object: X509TrustManager{
            override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {

            }

            override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {

            }

            override fun getAcceptedIssuers(): Array<X509Certificate?> {
                val arrayOfNulls = arrayOfNulls<X509Certificate?>(0)
                return arrayOfNulls
            }

        })
        val sslContext: SSLContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, SecureRandom())
        val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
        OkHttpClient.Builder().apply {
            connectTimeout(10, TimeUnit.SECONDS)
            writeTimeout(10, TimeUnit.SECONDS)
            readTimeout(20, TimeUnit.SECONDS)
            addInterceptor(HttpLoggingInterceptor {
                ALog.i("HttpLoggingInterceptor", it)
            }.apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            hostnameVerifier { _, _ -> true }
            sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
        }.build()

    }

    private val retrofit: Retrofit = Retrofit.Builder()
        .callFactory(okHttpClient)
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()

    fun <T> of(tClass: Class<T>): T {
        return retrofit.create(tClass)
    }
}